<?php
if ( IPB_THIS_SCRIPT != 'admin' )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'init.php'.";
	exit();
}

class ad_tools
{
	var $ipsclass;
	
	function auto_run()
	{
		$code_redirect = array(
								'list' => 'list_options',
								'convert' => 'convert_money',
								'inventory' => 'empty_inventory',
								'money' => 'set_money',
								'recount' => 'recount_money',
								'clean' => 'clean_up',
							);
		if(!$code_redirect[$this->ipsclass->input['do']])
		{
			$this->ipsclass->input['do'] = 'list';
		}
		$run = $code_redirect[$this->ipsclass->input['do']];
		$this->$run();		
	}
	
	function list_options()
	{
		$this->ipsclass->admin->page_title  = "Welcome to the tools page for ibMarket";
		$this->ipsclass->admin->page_detail = "Welcome to the tools page for ibMarket. Remember to backup your site and turn your board offline before applying any of these operations";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=tools', 'Tools' );
		
		$fields = array();
		$no_fields = array('mgroup', 'joined', 'dst_in_use', 'allow_admin_mails','email_pm', 'email_full', 'skin', 'warn_level', 'warn_lastwarn', 'last_post', 'view_sigs', 'view_img', 'view_avs', 'view_pop', 'bday_day', 'bday_month', 'bday_year', 'new_msg', 'msg_total', 'show_popup', 'last_visit', 'last_activity', 'coppa_user', 'sub_end', 'member_login_key_expire', 'subs_pkg_chosen', 'has_blog', 'has_gallery', 'members_auto_dst', 'members_created_remote', 'members_disable_pm', 'failed_login_count', 'members_profile_views');
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'members'));
		$mem_fields = $this->ipsclass->DB->get_result_fields($this->ipsclass->DB->exec_query());
		foreach($mem_fields as $field)
		{
			if((isset($field->numeric) && !$field->numeric) || $field->unique_key || $field->primary_key || in_array($field->name,$no_fields) || (is_string($field->type) && strstr($field->type,'int') === FALSE) || (is_numeric($field->type) && in_array($field->type,array(0,3,4,5,8))))
			{
				continue;
			}
			
			if(strstr('time',$field->name) !== FALSE)
			{
				continue;
			}
			
			if($field->name == $this->ipsclass->vars['market_members_field'])
			{
				continue;
			}
			
			$fields[$field->name] = $field;
		}
		
		$dropdown = array();
		$this->ipsclass->DB->build_query_from_cache('get_full_fields',array('table'=>'members'),'sql_market_queries');
		$mem_fields = $this->ipsclass->DB->exec_query();
		while($field = $this->ipsclass->DB->fetch_row())
		{
			if(!isset($fields[$field['Field']]) || strstr($field['Type'],'tiny') !== FALSE || strstr($field['Type'],'small') !== FALSE || strstr($field['Type'],'medium') !== FALSE)
			{
				continue;
			}
			$dropdown[] = array($field['Field'],$field['Field']." [".$field['Type']."]\n");
		}
		
		$this->ipsclass->html .= "<table border='0' width='100%'>\n";
		$this->ipsclass->html .= "<tr>\n<td width='49%' valign='top'>\n";

		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'  ),
																			 2 => array( 'act'       , 'market'      ),
																			 3 => array( 'code'      , 'tools'       ),
																			 4 => array( 'do'        , 'convert'     ),
																			 5 => array( 'direction' , 'to'          ),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Converting other money to ibMarket money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Source money",
																			$this->ipsclass->adskin->form_dropdown("other_field", $dropdown),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"ibMarket:Source money ratio",
																			$this->ipsclass->adskin->form_simple_input("ratio_market", 1).":".$this->ipsclass->adskin->form_simple_input("ratio_other", 1),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Empty Source money",
																			$this->ipsclass->adskin->form_dropdown("empty", array(array(0,'No'),array(1,'Yes'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Add/Replace to ibMarket money",
																			$this->ipsclass->adskin->form_dropdown("replace", array(array(0,'Add to'),array(1,'Replace'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Convert Money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= "</td><td width='2%'><!-- --></td><td width='49%' valign='top'>";

		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'  ),
																			 2 => array( 'act'       , 'market'      ),
																			 3 => array( 'code'      , 'tools'       ),
																			 4 => array( 'do'        , 'convert'     ),
																			 5 => array( 'direction' , 'from'        ),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Converting ibMarket money to another money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Target money",
																			$this->ipsclass->adskin->form_dropdown("other_field", $dropdown),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"ibMarket:Target money ratio",
																			$this->ipsclass->adskin->form_simple_input("ratio_market", 1).":".$this->ipsclass->adskin->form_simple_input("ratio_other", 1),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Empty ibMarket money",
																			$this->ipsclass->adskin->form_dropdown("empty", array(array(0,'No'),array(1,'Yes'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Add/Replace to target money",
																			$this->ipsclass->adskin->form_dropdown("replace", array(array(0,'Add to'),array(1,'Replace'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Convert Money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= "</td></tr><tr><td width='49%' valign='top'>";
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'  ),
																			 2 => array( 'act'       , 'market'      ),
																			 3 => array( 'code'      , 'tools'       ),
																			 4 => array( 'do'        , 'inventory'   ),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Empty Item Inventory");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Pay back member",
																			$this->ipsclass->adskin->form_dropdown("pay_back", array(array(0,'No money'),array(1,'Inventory resold price'),array(2,'Inventory bought price'),array(3,'Item listed resell price'),array(4,'Item listed buying price'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Return Item to stock?",
																			$this->ipsclass->adskin->form_dropdown("stock", array(array(0,'No'),array(1,'Yes'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Empty Inventory");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= "</td><td width='2%'><!-- --></td><td width='49%' valign='top'>";

		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'  ),
																			 2 => array( 'act'       , 'market'      ),
																			 3 => array( 'code'      , 'tools'       ),
																			 4 => array( 'do'        , 'money'       ),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Reset/Add Money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Add/Replace current money",
																			$this->ipsclass->adskin->form_dropdown("reset", array(array(0,'Add to'),array(1,'Reset'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"How much money",
																			$this->ipsclass->adskin->form_simple_input("money",0),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Reset/Add Money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= "</td></tr><tr><td width='49%' valign='top'>";
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'  ),
																			 2 => array( 'act'       , 'market'      ),
																			 3 => array( 'code'      , 'tools'       ),
																			 4 => array( 'do'        , 'clean'       ),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Clean Up");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("This will remove any thing that is associated with deleted members except logs.");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Clean Up");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= "</td><td width='2%'><!-- --></td><td width='49%' valign='top'>";

		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'  ),
																			 2 => array( 'act'       , 'market'      ),
																			 3 => array( 'code'      , 'tools'       ),
																			 4 => array( 'do'        , 'recount'     ),
																	)		);
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Recount Post Money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"Add/Replace current money",
																			$this->ipsclass->adskin->form_dropdown("reset", array(array(0,'Add to'),array(1,'Reset'))),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form("Reset/Add Money");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= "</td></tr></table>";
		
		$this->ipsclass->admin->output();
	}
	
	function convert_money()
	{
		if($this->ipsclasss->input['direction'] == 'to')
		{
			$to = $this->ipsclass->vars['market_members_field'];
			$from = $this->ipsclass->input['other_field'];
			$ratio = $this->ipsclass->numbers->divide($this->ipsclass->input['ratio_market'],$this->ipsclass->input['ratio_other']);
		}
		else
		{
			$from = $this->ipsclass->vars['market_members_field'];
			$to = $this->ipsclass->input['other_field'];
			$ratio = $this->ipsclass->numbers->divide($this->ipsclass->input['ratio_other'],$this->ipsclass->input['ratio_market']);
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('update'=>'members','set'=>$to."=".(!$this->ipsclass->input['replace'] ? $to."+" : "").$from."*".$ratio));
		
		if($this->ipsclass->input['empty'])
		{
			$this->ipsclass->DB->do_update('members',array(
																$from => 0,
											)				);
		}
		
		$this->ipsclass->admin->save_log("ibMarket: Money Converted");
			
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=tools","Money Converted...");
	}
	
	function empty_inventory()
	{
		$inv_ids = array();
		$member_add_money = array();
		$stock = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_inventory','order'=>'member_id DESC, item DESC','limit'=>array(250)));
		$this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_inventory'));
			
			$this->ipsclass->admin->save_log("ibMarket: Inventory Emptied");
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=tools","Inventory emptied...");
		}
		
		while($inv_item = $this->ipsclass->DB->fetch_row())
		{
			$inv_ids[$inv_item['i_id']] = $inv_item['i_id'];
			if($this->ipsclass->input['pay_back'] == 1)
			{
				$member_add_money[$inv_item['member_id']] = $this->ipsclass->numbers->add($member_add_money[$inv_item['member_id']],$inv_item['resell_price']);
			}
			elseif($this->ipsclass->input['pay_back'] == 2)
			{
				$member_add_money[$inv_item['member_id']] = $this->ipsclass->numbers->add($member_add_money[$inv_item['member_id']],$inv_item['price_bought']);
			}
			elseif($this->ipsclass->input['pay_back'] == 3)
			{
				$member_add_money[$inv_item['member_id']] = $this->ipsclass->numbers->add($member_add_money[$inv_item['member_id']],$this->ipsclass->cache['market_items'][$inv_item['item']]['resell']);
			}
			elseif($this->ipsclass->input['pay_back'] == 4)
			{
				$member_add_money[$inv_item['member_id']] = $this->ipsclass->numbers->add($member_add_money[$inv_item['member_id']],$this->ipsclass->cache['market_items'][$inv_item['item']]['price']);
			}
			if($this->ipsclass->input['stock'])
			{
				$stock[$inv_item['item']]++;
			}
		}
		
		if($this->ipsclass->input['pay_back'])
		{
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'members','where'=>"id IN (".implode(", ",array_keys($member_add_money)).")"));
			$mem = $this->ipsclass->DB->exec_query();
			while($member = $this->ipsclass->DB->fetch_row($mem))
			{
				$this->ipsclass->DB->do_update('members',array($this->ipsclass->vars['market_members_field']=>$this->ipsclass->numbers->add($member[$this->ipsclass->vars['market_members_field']],$member_add_money[$member['id']])),"id=".$member['id']);
			}
		}
		
		if($this->ipsclass->input['stock'])
		{
			foreach($stock as $item => $how_much)
			{
				if($this->ipsclass->cache['market_items'][$item]['stock'] >= 0)
				{
					$this->ipsclass->DB->do_update('market_items',array('stock'=>$this->ipsclass->cache['market_items'][$item]['stock']+$how_much),"item_id=".$item);
				}
			}
			
			$this->ipsclass->market_class->cache_items();
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_inventory','where'=>"i_id IN (".implode(", ",$inv_ids).")"));
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=tools&do=inventory&","Emptying Inventory...");
	}
	
	function set_money()
	{
		$this->ipsclass->money['money'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->money['money'],'int');
		
		$this->ipsclass->DB->build_and_exec_query(array('update'=>'members','set'=>$this->ipsclass->vars['market_members_field']."=".($this->ipsclass->input['reset'] ? "" : $this->ipsclass->vars['market_members_field']."+").$this->ipsclass->money['money']));
		
		if($this->ipsclass->input['reset'])
		{
			$this->ipsclass->admin->save_log("ibMarket: Resetted Money to ".$this->ipsclass->money['money']);
		}
		else
		{
			$this->ipsclass->admin->save_log("ibMarket: Added ".$this->ipsclass->money['money']." to everyone's money");
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=tools","Inventory emptied...");
	}
	
	function recount_money()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		if($this->ipsclass->input['reset'] AND $this->ipsclass->input['st'] == 0)
		{
			$this->ipsclass->DB->do_update('members',array($this->ipsclass->vars['market_members_field']=>0));
		}
		
		$members = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'posts','order'=>'pid ASC','limit'=>array($this->ipsclass->input['st'],250)));
		$this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->admin->save_log("ibMarket: Money recounted");
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=tools","Money recounted...");
		}
		
		while($post = $this->ipsclass->DB->fetch_row())
		{
			if($post['new_topic'])
			{
				if($this->ipsclass->forums->forum_by_id[$post['forum_id']]['market_topic'])
				{
					$more_more_money = $this->ipsclass->forums->forum_by_id[$post['forum_id']]['market_topic_amount'];
				}
				else
				{
					$more_more_money = $this->ipsclass->vars['market_post_topic'];
				}
			}
			else
			{
				if($this->ipsclass->forums->forum_by_id[$post['forum_id']]['market_reply'])
				{
					$more_more_money = $this->ipsclass->forums->forum_by_id[$post['forum_id']]['market_reply_amount'];
				}
				else
				{
					$more_more_money = $this->ipsclass->vars['market_post_reply'];
				}
			}
			$members[$post['author_id']] = $this->ipsclass->numbers->add($members[$post['author_id']],$more_more_money);
		}
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'members','where'=>"id IN (".implode(",",array_keys($members)).")"));
		$mems = $this->ipsclass->DB->exec_query();
		while($mem = $this->ipsclass->DB->fetch_row($mems))
		{
			$this->ipsclass->DB->do_update('members',array(
																$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->add($mem[$this->ipsclass->vars['market_members_field']],$members[$mem['id']])
										),"id=".$mem['id']);
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=tools&do=recount&st=".($this->ipsclass->input['st']+250),"Money being recounted...");
	}
	
	function clean_up()
	{
		$inv_id = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 'i.i_id',
												'from' => array('market_inventory'=>'i'),
												'where' => "m.id IS NULL",
												'add_join' => array(
																		array(
																				'select' => 'm.id',
																				'from' => array('members'=>'m'),
																				'where' => "i.member_id=m.id",
																				'type' => 'left',
																			),
																	),
										)	);
		$this->ipsclass->DB->exec_query();
		while($inv = $this->ipsclass->DB->fetch_row())
		{
			$inv_id[] = $inv['i_id'];
		}
		
		$this->ipsclass->DB->build_query(array(
												'select' => 'i.i_id',
												'from' => array('market_inventory'=>'i'),
												'where' => "j.item_id IS NULL",
												'add_join' => array(
																		array(
																				'select' => 'j.item_id',
																				'from' => array('market_items'=>'j'),
																				'where' => "i.item=j.item_id",
																				'type' => 'left',
																			),
																	),
										)	);
		$this->ipsclass->DB->exec_query();
		while($inv = $this->ipsclass->DB->fetch_row())
		{
			$inv_id[] = $inv['i_id'];
		}
		
		if(count($inv_id) > 0)
		{
			$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_inventory','where'=>"i_id IN (".implode(", ",$inv_id).")"));
		}
		
		$wage_id = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 'w.w_id',
												'from' => array('market_wages'=>'w'),
												'where' => "m.id IS NULL",
												'add_join' => array(
																		array(
																				'select' => 'm.id',
																				'from' => array('members'=>'m'),
																				'where' => "w.to_who='m' AND w.id_who=m.id",
																				'type' => 'left',
																			),
																	),
										)	);
		$this->ipsclass->DB->exec_query();
		while($wage = $this->ipsclass->DB->fetch_row())
		{
			$wage_id[] = $wage['w_id'];
		}
		
		if(count($wage_id) > 0)
		{
			$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_wages','where'=>"w_id IN (".implode(", ",$wage_id).")"));
		}
		
		if($this->ipsclass->market_class->count_plugin_filename("bank.php"))
		{
			$account_id = array();
			$this->ipsclass->DB->build_query(array(
													'select' => 'a.account_id',
													'from' => array('market_bank_accounts'=>'a'),
													'where' => "m.id IS NULL",
													'add_join' => array(
																			array(
																					'select' => 'm.id',
																					'from' => array('members'=>'m'),
																					'where' => "a.a_mem_id=m.id",
																					'type' => 'left',
																				),
																		),
											)	);
			$this->ipsclass->DB->exec_query();
			while($account = $this->ipsclass->DB->fetch_row())
			{
				$account_id[] = $account['account_id'];
			}
			
			if(count($account_id) > 0)
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_bank_accounts','where'=>"account_id IN (".implode(", ",$account_id).")"));
			}
		}
		
		if($this->ipsclass->market_class->count_plugin_filename("scratchcard.php"))
		{
			$ticket_id = array();
			$this->ipsclass->DB->build_query(array(
													'select' => 't.tick_id',
													'from' => array('market_scratchcard_ticket'=>'t'),
													'where' => "t.used = 0 AND m.id IS NULL",
													'add_join' => array(
																			array(
																					'select' => 'm.id',
																					'from' => array('members'=>'m'),
																					'where' => "t.member_id=m.id",
																					'type' => 'left',
																				),
																		),
											)	);
			$this->ipsclass->DB->exec_query();
			while($ticket = $this->ipsclass->DB->fetch_row())
			{
				$ticket_id[] = $ticket['tick_id'];
			}
			
			if(count($ticket_id) > 0)
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_scratchcard_ticket','where'=>"tick_id IN (".implode(", ",$ticket_id).")"));
			}
		}
		
		$this->ipsclass->admin->save_log("ibMarket: Clean up");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=tools","Clean up done...");
	}
}
?>